package com.open.api.ftp.util;

import com.open.api.ftp.common.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class FtpUtil {

/*

	public FtpUtil() {
		ftp = new FTPClient();
		//解决上传文件时文件名乱码
		ftp.setControlEncoding("UTF-8");
	}

	public FtpUtil(String controlEncoding) {
		ftp = new FTPClient();
		//解决上传文件时文件名乱码
		ftp.setControlEncoding(controlEncoding);
	}
*/

	public void setTimeOut(FTPClient ftp, int defaultTimeoutSecond, int connectTimeoutSecond, int dataTimeoutSecond){
		try {
			ftp.setDefaultTimeout(defaultTimeoutSecond * 1000);
			//commons-net-3.5.jar
			//ftp.setConnectTimeout(connectTimeoutSecond * 1000);
			//commons-net-1.4.1.jar 连接后才能设置
			ftp.setSoTimeout(connectTimeoutSecond * 1000);
			ftp.setDataTimeout(dataTimeoutSecond * 1000);
		} catch (SocketException e) {
			log.error("setTimeout Exception:", e);
		}
	}
/*

	public FTPClient getFTPClient(){
		return ftp;
	}

	public void setControlEncoding(String charset){
		ftp.setControlEncoding(charset);
	}

	public void setFileType(int fileType) throws IOException {
		ftp.setFileType(fileType);
	}
*/

	/**
	 * Connect to FTP server.
	 *
	 * @param host
	 *            FTP server address or name
	 * @param port
	 *            FTP server port
	 * @param user
	 *            user name
	 * @param password
	 *            user password
	 * @throws IOException
	 *             on I/O errors
	 */
	public ResponseData connect(String host, int port, String user, String password) throws IOException {
		ResponseData responseData=new ResponseData();
		FTPClient ftp=new FTPClient();
		// Connect to server.
		try {
			ftp.connect(host, port);
			//解决上传文件时文件名乱码
			ftp.setControlEncoding("UTF-8");

		} catch (UnknownHostException ex) {
			//throw new IOException("Can't find FTP server '" + host + "'");
			responseData.setCode(4);
			responseData.setMsg("connect异常："+ ex.getMessage());
			return  responseData;
		}

		// Check rsponse after connection attempt.
		int reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			disconnect(ftp);
			//throw new IOException("Can't connect to server '" + host + "'");
			responseData.setCode(1);
			responseData.setMsg("Can't connect to server '" + host + "'");
			return  responseData;
		}

		if ("".equals(user)) {
			user = "anonymous";
		}

		// Login.
		if (!ftp.login(user, password)) {
			disconnect(ftp);
		//	throw new IOException("Can't login to server '" + host + "'");
			responseData.setCode(1);
			responseData.setMsg("Can't login to server '" + host + "'");
			return  responseData;
		}

		// Set data transfer mode.
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		//ftp.setFileType(FTP.ASCII_FILE_TYPE);

		// Use passive mode to pass firewalls.
		ftp.enterLocalPassiveMode();

		//return ftp;
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		responseData.setData(ftp);
		return  responseData;
	}

	/**
	 * Test connection to ftp server
	 *
	 * @return true, if connected
	 */
	/*
	public boolean isConnected() {
		return ftp.isConnected();
	}
*/
	/**
	 * Disconnect from the FTP server
	 *
	 * @throws IOException
	 *             on I/O errors
	 */
	public ResponseData disconnect(FTPClient ftp) throws IOException {
		ResponseData responseData=new ResponseData();
		if (ftp.isConnected()) {
			try {
				ftp.logout();
				ftp.disconnect();
			} catch (IOException ex) {
				responseData.setCode(4);
				responseData.setMsg("disconnect异常："+ex.getMessage());
				return  responseData;
			}
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return  responseData;
	}

	/**
	 * Get file from ftp server into given output stream
	 *
	 * @param ftpFileName
	 *            file name on ftp server
	 * @param out
	 *            OutputStream
	 * @throws IOException
	 */
	public ResponseData retrieveFile(FTPClient ftp, String ftpFileName, OutputStream out) throws IOException {
		ResponseData responseData=new ResponseData();
		try {
			// Get file info.
			FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
			if (fileInfoArray == null || fileInfoArray.length == 0) {
				//throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server.");
				responseData.setCode(1);
				responseData.setMsg("File '" + ftpFileName + "' was not found on FTP server.");
				return responseData;
			}

			// Check file size.
			FTPFile fileInfo = fileInfoArray[0];
			long size = fileInfo.getSize();
			if (size > Integer.MAX_VALUE) {
				//throw new IOException("File '" + ftpFileName + "' is too large.");
				responseData.setCode(1);
				responseData.setMsg("File '" + ftpFileName + "' is too large.");
				return responseData;
			}

			// Download file.
			if (!ftp.retrieveFile(ftpFileName, out)) {
				//throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");
				responseData.setCode(1);
				responseData.setMsg("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");
				return responseData;
			}

			out.flush();

		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException ex) {
					responseData.setCode(4);
					responseData.setMsg(ex.getMessage());
					return responseData;
				}
			}
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * Put file on ftp server from given input stream
	 *
	 * @param ftpFileName
	 *            file name on ftp server
	 * @param in
	 *            InputStream
	 * @throws IOException
	 */
	public ResponseData storeFile(FTPClient ftp, String ftpFileName, InputStream in) throws IOException {
		ResponseData responseData=new ResponseData();
		try {
			if (!ftp.storeFile(ftpFileName, in)) {
				//throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
				responseData.setCode(1);
				responseData.setMsg("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
				return responseData;
			}
		} finally {
			try {
				in.close();
			} catch (IOException ex) {
				responseData.setCode(4);
				responseData.setMsg(ex.getMessage());
				return responseData;
			}
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * 修改名称
	 * @param from
	 * @param to
	 * @throws IOException
	 */
	public boolean rename(FTPClient ftp, String from, String to) throws IOException {
		return ftp.rename(from, to);
	}

	/**
	 * Delete the file from the FTP server.
	 *
	 * @param ftpFileName
	 *            server file name (with absolute path)
	 * @throws IOException
	 *             on I/O errors
	 */
	public ResponseData deleteFile(FTPClient ftp, String ftpFileName) throws IOException {
		ResponseData responseData=new ResponseData();
		if (!ftp.deleteFile(ftpFileName)) {
			//throw new IOException("Can't remove file '" + ftpFileName + "' from FTP server.");
			responseData.setCode(1);
			responseData.setMsg("Can't remove file '" + ftpFileName + "' from FTP server.");
			return responseData;
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * 删除
	 * @param ftpFileName
	 * @return
	 */
	public ResponseData defaultDeleteFile(String ftpUrl,Integer ftpPort,String ftpUsername,String ftpPassword,String basePath,String ftpFileName) {
		ResponseData responseData=new ResponseData();
		FTPClient ftp=new FTPClient();
		try {
			responseData=connect(ftpUrl,ftpPort,ftpUsername,ftpPassword);
			if(responseData.getCode()!=0){
				return responseData;
			}else{
				ftp= (FTPClient) responseData.getData();
			}
			responseData=deleteFile(ftp,basePath + ftpFileName);
			if(responseData.getCode()!=0){
				return  responseData;
			}
			responseData=disconnect(ftp);
			if(responseData.getCode()!=0){
				return  responseData;
			}
		} catch (IOException e) {
			responseData.setCode(4);
			responseData.setMsg(e.getMessage());
			return  responseData;
		}

		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return  responseData;
	}

	/**
	 * Upload the file to the FTP server.
	 *
	 * @param ftpFileName
	 *            server file name (with absolute path)
	 * @param localFile
	 *            local file to upload
	 * @throws IOException
	 *             on I/O errors
	 */
	public ResponseData upload(FTPClient ftp, String ftpFileName, File localFile) throws IOException {
		ResponseData responseData=new ResponseData();
		// File check.
		if (!localFile.exists()) {
		//	throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");
			responseData.setCode(1);
			responseData.setMsg("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");
			return  responseData;
		}

		// Upload.
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(localFile));
			if (!ftp.storeFile(ftpFileName, in)) {
				//throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
				responseData.setCode(101);
				responseData.setMsg("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
				return  responseData;
			}

		} finally {
			try {
				in.close();
			} catch (IOException ex) {
				responseData.setCode(4);
				responseData.setMsg(ex.getMessage());
				return  responseData;
			}
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return  responseData;
	}

	private ResponseData upload(FTPClient ftp, String basePath, String filePath, String fileName, File uploadFile) throws IOException {
		System.out.println("basePath = " + basePath + ", filePath = " + filePath + ", fileName = " + fileName + ", uploadFile = " + uploadFile);
		ResponseData responseData=new ResponseData();
		String remoteRelativeFilePath =  basePath + filePath;

		responseData=mkDir(ftp,basePath, filePath);
		if(responseData.getCode()!=0){
			return responseData;
		}

		responseData=upload(ftp,remoteRelativeFilePath + fileName, uploadFile);
		if(responseData.getCode()!=0){
			return responseData;
		}

		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}


  private ResponseData mkDir(FTPClient ftp, String basePath, String filePath)  {

  	ResponseData responseData=new ResponseData();
		//先切换到根目录
	  boolean changeDirFlag = false;
	  try {
		  changeDirFlag = ftp.changeWorkingDirectory(basePath);
	  } catch (IOException e) {
		  responseData.setCode(4);
		  responseData.setMsg("mkDir--changeWorkingDirectory异常："+e.getMessage());
		  return responseData;
	  }
	  if (!changeDirFlag){
		//	throw new PiiumsException("根目录: " + basePath + "访问失败");
			System.out.println("根目录: " + basePath + "访问失败");
		  responseData.setCode(1);
		  responseData.setMsg("根目录: " + basePath + "访问失败");
		  return responseData;
		}
		String[] dirs = filePath.split("/");
		// 一层层判定目录是否存在
		for (int i = 0; i < dirs.length; i++){
			boolean isExist = false;
			try {
				isExist = ftp.changeWorkingDirectory( dirs[i]);
			} catch (IOException e) {
				responseData.setCode(4);
				responseData.setMsg("mkDir--changeWorkingDirectory-isExist异常："+e.getMessage());
				return responseData;
			}
			if (isExist){
				continue;
			}else {
				try {
					ftp.makeDirectory(dirs[i]);
					ftp.changeWorkingDirectory(dirs[i]);
				} catch (IOException e) {
					e.printStackTrace();
					responseData.setCode(4);
					responseData.setMsg("mkDir--changeWorkingDirectory-isExist异常："+e.getMessage());
					return responseData;
				}

			}
			i++;
		}

		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * 上传目录（会覆盖)
	 * @param remotePath 远程目录 /home/test/a
	 * @param localPath 本地目录 D:/test/a
	 * @throws IOException
	 */
	public ResponseData uploadDir(FTPClient ftp, String remotePath, String localPath) throws IOException {
		ResponseData responseData=new ResponseData();
		File file = new File(localPath);
		if (file.exists()) {
			if(!ftp.changeWorkingDirectory(remotePath)){
				//创建成功返回true，失败（已存在）返回false
				ftp.makeDirectory(remotePath);
				//切换成返回true，失败（不存在）返回false
				ftp.changeWorkingDirectory(remotePath);
			}
			File[] files = file.listFiles();
			for (File f : files) {
				if (f.isDirectory() && !f.getName().equals(".") && !f.getName().equals("..")) {
					uploadDir(ftp,remotePath + "/" + f.getName(), f.getPath());
				} else if (f.isFile()) {
					upload(ftp,remotePath + "/" + f.getName(), f);
				}
			}
		}

		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * Download the file from the FTP server.
	 *
	 * @param ftpFileName
	 *            server file name (with absolute path)
	 * @param localFile
	 *            local file to download into
	 * @throws IOException
	 *             on I/O errors
	 */
	public ResponseData download(FTPClient ftp, String ftpFileName, File localFile) throws IOException {
		ResponseData responseData=new ResponseData();
		// Download.
		OutputStream out = null;
		try {
			// Get file info.
			FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
			if (fileInfoArray == null || fileInfoArray.length == 0) {
				//throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");
				responseData.setCode(1);
				responseData.setMsg("File " + ftpFileName + " was not found on FTP server.");
				return responseData;
			}

			// Check file size.
			FTPFile fileInfo = fileInfoArray[0];
			long size = fileInfo.getSize();
			if (size > Integer.MAX_VALUE) {
				//throw new IOException("File " + ftpFileName + " is too large.");
				responseData.setCode(1);
				responseData.setMsg("File " + ftpFileName + " is too large.");
				return responseData;
			}

			// Download file.
			out = new BufferedOutputStream(new FileOutputStream(localFile));
			if (!ftp.retrieveFile(ftpFileName, out)) {
				//throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");
				responseData.setCode(1);
				responseData.setMsg("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");
				return responseData;
			}

			out.flush();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException ex) {
					responseData.setCode(4);
					responseData.setMsg(ex.getMessage());
					return responseData;
				}
			}
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * 下载目录（会覆盖)
	 * @param remotePath 远程目录 /home/test/a
	 * @param localPath 本地目录 D:/test/a
	 * @return
	 * @throws IOException
	 */
	public ResponseData downloadDir(FTPClient ftp, String remotePath, String localPath) throws IOException {
		ResponseData responseData=new ResponseData();
		File file = new File(localPath);
		if(!file.exists()){
			file.mkdirs();
		}
		FTPFile[] ftpFiles = ftp.listFiles(remotePath);
		System.out.println("下载目录文件："+ftpFiles);
		System.out.println("下载目录文件："+ftpFiles.toString());
		System.out.println("下载目录文件："+ftpFiles.length);
		for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {
			FTPFile ftpFile = ftpFiles[i];
			System.out.println("下载目录文件中....["+(i+1)+"]:"+ftpFile.getName());
			if (ftpFile.isDirectory() && !ftpFile.getName().equals(".") && !ftpFile.getName().equals("..")) {
				responseData=downloadDir(ftp,remotePath + "/" + ftpFile.getName(), localPath + "/" + ftpFile.getName());
				if(responseData.getCode()!=0){
					return responseData;
				}else{
					System.out.println("...下载目录:"+ftpFile.getName()+" 成功！");
					responseData.setCode(0);
					responseData.setMsg("SUCCESS");
				}
			} else {
				responseData=download(ftp,remotePath + "/" + ftpFile.getName(), new File(localPath + "/" + ftpFile.getName()));
				if(responseData.getCode()!=0){
					return responseData;
				}else{
					System.out.println("...下载文件:"+ftpFile.getName()+" 成功！");
					responseData.setCode(0);
					responseData.setMsg("SUCCESS");
				}
			}
		}

		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}

	/**
	 * 下载目录（会覆盖)
	 * @param remotePath 远程目录 /home/test/a
	 * @param localPath 本地目录 D:/test/a
	 * @return
	 * @throws IOException
	 */
	public ResponseData downloadDir(FTPClient ftp, String basePath, String remotePath, String localPath) throws IOException {
		ResponseData responseData=new ResponseData();

		responseData=downloadDir(ftp,basePath + remotePath, localPath);
		return responseData;
	}

	/**
	 * List the file name in the given FTP directory.
	 *
	 * @param filePath
	 *            absolute path on the server
	 * @return files relative names list
	 * @throws IOException
	 *             on I/O errors
	 */
	public List<String> listFileNames(FTPClient ftp, String filePath) throws IOException {
		List<String> fileList = new ArrayList<>();

		FTPFile[] ftpFiles = ftp.listFiles(filePath);
		for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {
			FTPFile ftpFile = ftpFiles[i];
			if (ftpFile.isFile()) {
				fileList.add(ftpFile.getName());
			}
		}

		return fileList;
	}

	/**
	 * List the files in the given FTP directory.
	 *
	 * @param filePath
	 *            directory
	 * @return list
	 * @throws IOException
	 */
	public List<FTPFile> listFiles(FTPClient ftp, String filePath) throws IOException {
		List<FTPFile> fileList = new ArrayList<>();

		FTPFile[] ftpFiles = ftp.listFiles(filePath);
		for (int i = 0; ftpFiles!=null && i<ftpFiles.length; i++) {
			FTPFile ftpFile = ftpFiles[i];
//            FfpFileInfo fi = new FfpFileInfo();
//            fi.setName(ftpFile.getName());
//            fi.setSize(ftpFile.getSize());
//            fi.setTimestamp(ftpFile.getTimestamp());
//            fi.setType(ftpFile.isDirectory());
			fileList.add(ftpFile);
		}

		return fileList;
	}


	/**
	 * Send an FTP Server site specific command
	 *
	 * @param args
	 *            site command arguments
	 * @throws IOException
	 *             on I/O errors
	 */
	public void sendSiteCommand(FTPClient ftp, String args) throws IOException {
		if (ftp.isConnected()) {
			try {
				ftp.sendSiteCommand(args);
			} catch (IOException ex) {
			}
		}
	}

	/**
	 * Get current directory on ftp server
	 *
	 * @return current directory
	 */
	public String printWorkingDirectory(FTPClient ftp) {
		if (!ftp.isConnected()) {
			return "";
		}

		try {
			return ftp.printWorkingDirectory();
		} catch (IOException e) {
		}

		return "";
	}

	/**
	 * Set working directory on ftp server
	 *
	 * @param dir
	 *            new working directory
	 * @return true, if working directory changed
	 */
	public boolean changeWorkingDirectory(FTPClient ftp, String dir) {
		if (!ftp.isConnected()) {
			return false;
		}

		try {
			return ftp.changeWorkingDirectory(dir);
		} catch (IOException e) {
		}

		return false;
	}

	/**
	 * Change working directory on ftp server to parent directory
	 *
	 * @return true, if working directory changed
	 */
	public boolean changeToParentDirectory(FTPClient ftp) {
		if (!ftp.isConnected()) {
			return false;
		}

		try {
			return ftp.changeToParentDirectory();
		} catch (IOException e) {
		}

		return false;
	}

	/**
	 * Get parent directory name on ftp server
	 *
	 * @return parent directory
	 */
	public String printParentDirectory(FTPClient ftp) {
		if (!ftp.isConnected()) {
			return "";
		}

		String w = printWorkingDirectory(ftp);
		changeToParentDirectory(ftp);
		String p = printWorkingDirectory(ftp);
		changeWorkingDirectory(ftp,w);

		return p;
	}

	/**
	 * 上传目录
	 * @param remoteFilePath
	 * @param fileName
	 * @param uploadFile
	 * @throws IOException
	 */
	public ResponseData defaultUpload(String ftpUrl,Integer ftpPort,String ftpUsename,String ftpPassword,String basePath,
                              String remoteFilePath, String fileName, File uploadFile){

		System.out.println("上传ftp开始.....");
		FTPClient ftp=new FTPClient();
		ResponseData responseData=new ResponseData();
		try {
			responseData=connect(ftpUrl,ftpPort,ftpUsename,ftpPassword);
			if(responseData.getCode()!=0){
				return responseData;
			}else {
				ftp= (FTPClient) responseData.getData();
			}
			responseData=upload(ftp,basePath, remoteFilePath, fileName, uploadFile);
			if(responseData.getCode()!=0){
				return responseData;
			}
			responseData=disconnect(ftp);
			if(responseData.getCode()!=0){
				return responseData;
			}
		} catch (IOException e) {
			responseData.setCode(4);
			responseData.setMsg(e.getMessage());
			return  responseData;
		}


		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return  responseData;
	}


  public ResponseData defaultDownloadDir(String ftpUrl,Integer ftpPort,String ftpUsename,String ftpPassword,String basePath, String remotePath, String localPath) {
	  ResponseData responseData=new ResponseData();
	  FTPClient ftp=new FTPClient();
	  try {
		  responseData=connect(ftpUrl,ftpPort,ftpUsename,ftpPassword);
		  if(responseData.getCode()!=0){
			  return responseData;
		  }else{
		  	ftp= (FTPClient) responseData.getData();
		  }
		  responseData=downloadDir(ftp,basePath, remotePath, localPath);
		  if(responseData.getCode()!=0){
			  return responseData;
		  }
		  responseData=disconnect(ftp);
		  if(responseData.getCode()!=0){
			  return responseData;
		  }
	  } catch (IOException e) {
		  responseData.setCode(4);
		  responseData.setMsg(e.getMessage());
		  return  responseData;
	  }

	  responseData.setCode(0);
	  responseData.setMsg("SUCCESS");
	  return  responseData;
  }


  /**
	 * 删除服务器的文件
	 *
	 * @param ftpClient   连接成功且有效的 FTP客户端
	 * @param deleteFiles 待删除的文件或者目录，为目录时，会逐个删除，
	 *                    路径必须是绝对路径，如 "/1.png"、"/video/3.mp4"、"/images/2018"
	 *                    "/" 表示用户根目录,则删除所有内容
	 */
	//public static void deleteServerFiles(FTPClient ftpClient, String deleteFiles) {
	public  void deleteServerFiles(FTPClient ftpClient, String deleteFiles) {
		/**如果 FTP 连接已经关闭，或者连接无效，则直接返回*/
		if (!ftpClient.isConnected() || !ftpClient.isAvailable()) {
			System.out.println(">>>>>FTP服务器连接已经关闭或者连接无效*****放弃文件上传****");
			return;
		}
		try {
			/** 尝试改变当前工作目录到 deleteFiles
			 * 1）changeWorkingDirectory：变更FTPClient当前工作目录，变更成功返回true，否则失败返回false
			 * 2）如果变更工作目录成功，则表示 deleteFiles 为服务器已经存在的目录
			 * 3）否则变更失败，则认为 deleteFiles 是文件，是文件时则直接删除
			 */
			boolean changeFlag = ftpClient.changeWorkingDirectory(deleteFiles);
			if (changeFlag) {
				/**当被删除的是目录时*/
				FTPFile[] ftpFiles = ftpClient.listFiles();
				for (FTPFile ftpFile : ftpFiles) {
					System.out.println("----------------::::" + ftpClient.printWorkingDirectory());
					if (ftpFile.isFile()) {
						boolean deleteFlag = ftpClient.deleteFile(ftpFile.getName());
						if (deleteFlag) {
							System.out.println(">>>>>删除服务器文件成功****" + ftpFile.getName());
						} else {
							System.out.println(">>>>>删除服务器文件失败****" + ftpFile.getName());
						}
					} else {
						/**printWorkingDirectory：获取 FTPClient 客户端当前工作目录
						 * 然后开始迭代删除子目录
						 */
						String workingDirectory = ftpClient.printWorkingDirectory();
						deleteServerFiles(ftpClient, workingDirectory + "/" + ftpFile.getName());
					}
				}
				/**printWorkingDirectory：获取 FTPClient 客户端当前工作目录
				 * removeDirectory：删除FTP服务端的空目录，注意如果目录下存在子文件或者子目录，则删除失败
				 * 运行到这里表示目录下的内容已经删除完毕，此时再删除当前的为空的目录，同时将工作目录移动到上移层级
				 * */
				String workingDirectory = ftpClient.printWorkingDirectory();
				ftpClient.removeDirectory(workingDirectory);
				ftpClient.changeToParentDirectory();
			} else {
				/**deleteFile：删除FTP服务器上的文件
				 * 1）只用于删除文件而不是目录，删除成功时，返回 true
				 * 2）删除目录时无效,方法返回 false
				 * 3）待删除文件不存在时，删除失败，返回 false
				 * */
				boolean deleteFlag = ftpClient.deleteFile(deleteFiles);
				if (deleteFlag) {
					System.out.println(">>>>>删除服务器文件成功****" + deleteFiles);
				} else {
					System.out.println(">>>>>删除服务器文件失败****" + deleteFiles);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除ftp服务器目录
	 * @param ftpFileName
	 * @return
	 */
	public ResponseData deleteDIRAndFile(String ftpUrl,Integer ftpPort,String ftpUsename,String ftpPassword,String ftpFileName) {
		ResponseData responseData=new ResponseData();
		FTPClient ftp=new FTPClient();
		try {
			responseData=connect(ftpUrl,ftpPort,ftpUsename,ftpPassword);
			if(responseData.getCode()!=0){
				return responseData;
			}else{
				ftp= (FTPClient) responseData.getData();
			}
			deleteServerFiles(ftp,ftpFileName);
			if(responseData.getCode()!=0){
				return  responseData;
			}
			responseData=disconnect(ftp);
			if(responseData.getCode()!=0){
				return  responseData;
			}
		} catch (IOException e) {
			responseData.setCode(4);
			responseData.setMsg(e.getMessage());
			return  responseData;
		}

		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return  responseData;
	}

	/**
	 * 删除ftp上文件
	 * @param map
	 * @param remotePath
	 * @param localPath
	 * @return
	 */
	public ResponseData cleanFtp(Map<String,Object> map,String ftpUrl,Integer ftpPort,String ftpUsename,String ftpPassword,String basePath,String remotePath,String localPath){
		ResponseData responseData=new ResponseData();

		ResponseData responseData_ftp=new ResponseData();
		FTPClient ftp=new FTPClient();

		// Get file info.
		try {
			responseData_ftp=connect(ftpUrl,ftpPort,ftpUsename,ftpPassword);
			if(responseData_ftp.getCode()==0){
				ftp= (FTPClient) responseData_ftp.getData();
			}else {
				return responseData_ftp;
			}
		} catch (IOException e) {
			System.out.println("connect---e="+e.getMessage());
			responseData.setCode(4);
			responseData.setMsg("连接FTP异常："+e.getMessage());
			return responseData;
		}

		boolean flag=true;
		FtpUtil ftpUtil=new FtpUtil();
		Integer folderCount= (Integer) map.get("folderCount");
		Integer fileCount= (Integer) map.get("fileCount");
		List fileNameList=new ArrayList<>();
		List dirNameList=new ArrayList<>();
		dirNameList= (List) map.get("dirNameList");
		fileNameList= (List) map.get("fileNameList");
		//删除文件
		if(fileCount>0 && fileNameList!=null && fileNameList.size()>0){
			for(int i=0;i<fileNameList.size();i++){
				String fileName= (String) fileNameList.get(i);
				System.out.println("delete file :"+remotePath+fileName);
				/********************************************************/

				FTPFile[] fileInfoArray = new FTPFile[0];
				try {
					fileInfoArray = ftp.listFiles(remotePath+fileName);
					if (fileInfoArray == null || fileInfoArray.length == 0) {
						//throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");

						System.out.println("File =" + remotePath+fileName + " was not found on FTP server.");

						/*responseData=disconnect(ftp);
						if(responseData.getCode()!=0){
							return  responseData;
						}*/
						continue;
					}
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println("e="+e.getMessage());
				}
/*

				try {
					responseData=disconnect(ftp);
					if(responseData.getCode()!=0){
						return  responseData;
					}
				} catch (IOException e) {
					System.out.println("delete file disconnect e=="+e.getMessage());
					responseData.setCode(4);
					responseData.setMsg("delete file disconnect e=="+e.getMessage());
					return responseData;
				}
*/

				/********************************************************/
				responseData=ftpUtil.defaultDeleteFile(ftpUrl,ftpPort,ftpUsename,ftpPassword,basePath,remotePath+fileName);
				if(responseData.getCode()!=0){
					flag=false;
					break;
				}
			}
			if(!flag){
				return responseData;
			}
		}

		//删除目录下文件
		if(folderCount>0 && dirNameList!=null && dirNameList.size()>0){
			for(int i=0;i<dirNameList.size();i++){
				String dirName= (String) dirNameList.get(i);
				String dirPath=remotePath+dirName+"/";
				String localTmpPath=localPath+dirName+"/";
				FileIOUtil writeAndReadUtils=new FileIOUtil();
				Map localFilesMap=writeAndReadUtils.DirsAndFilesCount(localTmpPath);
				Integer code= (Integer) localFilesMap.get("code");
				if(code!=0){
					responseData.setCode(1);
					responseData.setData("删除目录下文件失败！");
					flag=false;
					break;
				}
				Integer localFileCount= (Integer) localFilesMap.get("fileCount");
				Integer localFolderCount= (Integer) localFilesMap.get("folderCount");
				List LocalFileNameList=new ArrayList();
				List LocalDirNameList=new ArrayList();
				LocalFileNameList= (List) localFilesMap.get("fileNameList");
				LocalDirNameList= (List) localFilesMap.get("dirNameList");
				if(localFileCount>0&& LocalFileNameList.size()>0){
					for(int j=0;j<LocalFileNameList.size();j++){
						String delfilename= (String) LocalFileNameList.get(j);
						String delPath=dirPath+delfilename;
						System.out.println("delete dir down file :"+delPath);
						/********************************************************/
						// Get file info.
						/*
						try {
							responseData=connect(host,port,username,password);
						} catch (IOException e) {
							e.printStackTrace();
							System.out.println("connect---e="+e.getMessage());
						}
						*/
						FTPFile[] fileInfoArray = new FTPFile[0];
						try {
							fileInfoArray = ftp.listFiles(delPath);
							if (fileInfoArray == null || fileInfoArray.length == 0) {
								//throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");

								System.out.println("File " + delPath + " was not found on FTP server.");
								/*
								responseData.setCode(1);
								responseData.setMsg("File " + delfilename + " was not found on FTP server.");
								return responseData;
								*/
                                 /*
								responseData=disconnect(ftp);
								if(responseData.getCode()!=0){
									return  responseData;
								}
								*/
								continue;
							}
						} catch (IOException e) {
							e.printStackTrace();
							System.out.println("e="+e.getMessage());
						}
/*
						try {
							responseData=disconnect(ftp);
							if(responseData.getCode()!=0){
								return  responseData;
							}
						} catch (IOException e) {
							//e.printStackTrace();
							System.out.println("delete dirfile disconnect e=="+e.getMessage());
							responseData.setCode(4);
							responseData.setMsg("delete dirfile disconnect e=="+e.getMessage());
							return responseData;
						}
                       */
						/********************************************************/
						responseData=defaultDeleteFile(ftpUrl,ftpPort,ftpUsename,ftpPassword,basePath,delPath);
						if(responseData.getCode()!=0){
							flag=false;
							break;
						}
					}
					if(!flag){
						break;
					}
				}
			}

			if(!flag){
				return responseData;
			}
		}

		try {
			responseData=disconnect(ftp);
			if(responseData.getCode()!=0){
				return  responseData;
			}
		} catch (IOException e) {
			//e.printStackTrace();
			System.out.println("delete dirfile disconnect e=="+e.getMessage());
			responseData.setCode(4);
			responseData.setMsg("delete dirfile disconnect e=="+e.getMessage());
			return responseData;
		}
		responseData.setCode(0);
		responseData.setMsg("SUCCESS");
		return responseData;
	}


	public static void main(String[] args) {
		FtpUtil ftpUtil=new FtpUtil();
		String ftpUrl="192.168.20.35";
		Integer ftpPort=9922;
		String ftpUsename="cetc";
		String ftpPassword="cetc@2020!";
		String ftpBasepath="/";
		String ftpSendpath="epms_images/";


		//ResponseData responseData=ftpUtil.defaultUpload(ftpUrl,ftpPort,ftpUsename,ftpPassword,ftpBasepath,ftpSendpath,"epms_place_DELETE_2020-05-29_1590746469716431346999.json",new File("H:\\send\\epms_place_DELETE_2020-05-29_159074646971643134699.json"));
		ResponseData responseData=ftpUtil.defaultUpload(ftpUrl,ftpPort,ftpUsename,ftpPassword,ftpBasepath,ftpSendpath,"11.jpg",new File("H:\\send\\11.jpg"));
		//ResponseData responseData=ftpUtil.defaultDownloadDir(FtpServerType.FROM_OUTSIDE_TO_INSIDE,"ftpFile/data/","H:/TT/");
		//ResponseData responseData=ftpUtil.defaultDownloadDir(FtpServerType.FROM_OUTSIDE_TO_INSIDE,"ftpFile/data/","H:/TT/");
		//ResponseData responseData=ftpUtil.defaultDeleteFile(FtpServerType.FROM_OUTSIDE_TO_INSIDE,"ftpFile/data/test123.txt");
		//ResponseData responseData=ftpUtil.deleteDIRAndFile(ftpUrl,ftpPort,ftpUsename,ftpPassword,"send");
		System.out.println("responseData.setMsg(); = " + responseData.toString());

	}
}
